package com.shelpe.service.simbaproxy.taobao;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.shelpe.service.simbaproxy.UtilsHelp;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Setter
@Slf4j
public class TaobaoAPIServiceImpl implements TaobaoAPIService {

	private TaobaoPropertiesProvider prop;

	@Override
	public URL getURL() {
		try {
			URL tabbaoUrl = new URL(this.prop.getUrl());
			return tabbaoUrl;
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return null;
	}

	@Override
	public void addCommParams(boolean isPurchaseUser, Map<String, List<String>> params) {

		List<String> app_keyList = new ArrayList<String>();
		app_keyList.add(isPurchaseUser?prop.getAppKey():prop.getProxyAppKey());
		params.put("app_key", app_keyList);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<String> timestampList = new ArrayList<String>();
		timestampList.add(sdf.format(new Date()));
		params.put("timestamp", timestampList);

		List<String> formatList = new ArrayList<String>();
		formatList.add(prop.getFormat());
		params.put("format", formatList);

		List<String> vList = new ArrayList<String>();
		vList.add(prop.getV());
		params.put("v", vList);

		List<String> sign_methodList = new ArrayList<String>();
		sign_methodList.add(prop.getSignMethod());
		params.put("sign_method", sign_methodList);

		try {

			Map<String, String> paramsMap = new HashMap<String, String>();
			Set<Entry<String, List<String>>> keyValueSet = params.entrySet();

			for (Entry<String, List<String>> item : keyValueSet) {
				List<String> values = item.getValue();
				String strValue = UtilsHelp.listToString(values);

				paramsMap.put(item.getKey(), strValue);
			}
			List<String> md5resList = new ArrayList<String>();
			String md5res = UtilsHelp.signTopRequest(paramsMap, isPurchaseUser?prop.getAppSecret():prop.getProxyAppSecret(), prop.getSignMethod());
			md5resList.add(md5res);
			params.put("sign", md5resList);

		} catch (NoSuchAlgorithmException e) {
			log.error("NoSuchAlgorithmException: ", e);
		} catch (IOException e) {
			log.error("IOException: ", e);
		}
	}
}
